package org.com.controller;

import io.swagger.annotations.Api;
import org.com.common.R;
import org.com.dto.ProductPurchaseDTO;
import org.com.pojo.Farms;
import org.com.pojo.ProductImages;
import org.com.pojo.Products;
import org.com.service.FarmsService;
import org.com.service.ProductImagesService;
import org.com.service.ProductsService;
import org.com.service.FavoritesService;
import org.com.pojo.Favorites;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.com.util.RedisUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(tags = "商品管理")
@RequestMapping("/api/products")
public class ProductsController {
    
    private static final String CART_KEY_PREFIX = "cart:";
    private static final String CART_SET_KEY_PREFIX = "cart_keys:";
    private static final int CART_EXPIRE_TIME = 300; // 5分钟过期

    @Autowired
    private ProductsService productsService;
    @Autowired
    private ProductImagesService productImagesService;

    @Autowired
    private FavoritesService favoritesService;
    
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private FarmsService farmsService;

    /**
     * 获取商品详情
     * @param productId 商品ID
     * @return 商品详情
     */
    @GetMapping("/detail/{productId}")
    public R getProductDetail(@PathVariable Integer productId) {
        log.info("获取商品详情, productId: {}", productId);
        return productsService.getProductDetail(productId);
    }
    
    /**
     * 获取农场的所有商品
     * @param farmId 农场ID
     * @return 商品列表
     */
    @GetMapping("/farm/{farmId}")
    public R getFarmProducts(@PathVariable Integer farmId) {
        log.info("获取农场商品列表, farmId: {}", farmId);
        return productsService.getFarmProducts(farmId);
    }
    
    /**
     * 获取当前用户的所有商品
     * @param userId 用户ID
     * @return 商品列表
     */
    @GetMapping("/user")
    public R getUserProducts(@RequestParam Integer userId) {
        log.info("获取用户商品列表, userId: {}", userId);
        return productsService.getUserProducts(userId);
    }
    
    /**
     * 创建商品
     * @param farmId 农场ID
     * @param productName 商品名称
     * @param productDescription 商品描述
     * @param price 价格
     * @param stock 库存
     * @param images 商品图片
     * @param categoryIds 分类ID列表
     * @return 创建的商品
     */
    @PostMapping("/farm/{farmId}")
    public R createProduct(
            @PathVariable Integer farmId,
            @RequestParam String productName,
            @RequestParam String productDescription,
            @RequestParam Double price,
            @RequestParam Integer stock,
            @RequestParam(required = false) List<MultipartFile> images,
            @RequestParam List<Integer> categoryIds
    ) {
        log.info("创建商品, farmId: {}, name: {}, price: {}, stock: {}, categoryIds: {}", 
            farmId, productName, price, stock, categoryIds);
        
        Products product = new Products();
        product.setFarmId(farmId);
        product.setProductName(productName);
        product.setProductDescription(productDescription);
        product.setPrice(price);
        product.setStock(stock);
        
        return productsService.createProduct(product, images, categoryIds);
    }
    
    /**
     * 删除商品
     * @param productId 商品ID
     * @return 删除结果
     */
    @DeleteMapping("/{productId}")
    public R deleteProduct(@PathVariable Integer productId) {
        log.info("删除商品, productId: {}", productId);
        return productsService.deleteProduct(productId);
    }
    
    @PutMapping("/stock/{productId}")
    public R updateProductStock(@PathVariable Integer productId, @RequestParam Integer stock) {
        return productsService.updateProductStock(productId, stock);
    }

    /**
     * 更新商品状态
     * @param productId 商品ID
     * @param status 状态：1-上架中，0-已下架
     * @return 更新结果
     */
    @PutMapping("/status/{productId}")
    public R updateProductStatus(@PathVariable Integer productId, @RequestParam Integer status) {
        log.info("更新商品状态, productId: {}, status: {}", productId, status);
        return productsService.updateProductStatus(productId, status);
    }
    
    @PostMapping("/favorites/add")
    public R addToFavorites(@RequestBody Map<String, Integer> params, HttpServletRequest request) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        Integer productId = params.get("productId");
        
        log.info("添加收藏, userId: {}, productId: {}", userId, productId);
        
        if (userId == null || productId == null) {
            return R.error("参数错误");
        }
        
        try {
            // 检查是否已经收藏
            LambdaQueryWrapper<Favorites> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Favorites::getUserId, userId)
                    .eq(Favorites::getProductId, productId);
            
            if (favoritesService.getOne(queryWrapper) != null) {
                return R.error("已经收藏过该商品");
            }
            
            // 添加收藏
            Favorites favorite = new Favorites();
            favorite.setUserId(userId);
            favorite.setProductId(productId);
            favorite.setCreatedAt(new Date());
            
            boolean result = favoritesService.save(favorite);
            if (result) {
                return R.success("收藏成功");
            } else {
                return R.error("收藏失败");
            }
        } catch (Exception e) {
            log.error("添加收藏失败", e);
            return R.error("收藏失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/favorites/remove")
    public R removeFromFavorites(@RequestBody Map<String, Integer> params, HttpServletRequest request) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        Integer productId = params.get("productId");
        
        log.info("取消收藏, userId: {}, productId: {}", userId, productId);
        
        if (userId == null || productId == null) {
            return R.error("参数错误");
        }
        
        try {
            LambdaQueryWrapper<Favorites> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Favorites::getUserId, userId)
                    .eq(Favorites::getProductId, productId);
            
            boolean result = favoritesService.remove(queryWrapper);
            if (result) {
                return R.success("取消收藏成功");
            } else {
                return R.error("取消收藏失败，记录不存在");
            }
        } catch (Exception e) {
            log.error("取消收藏失败", e);
            return R.error("取消收藏失败: " + e.getMessage());
        }
    }
    @GetMapping("/favorites/list")
    public R getFavoritesList(HttpServletRequest request) {
        try {
            // 获取当前用户ID
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            if (userId == null) {
                return R.error("用户未登录");
            }

            log.info("获取收藏列表, userId: {}", userId);

            // 查询用户的收藏记录
            LambdaQueryWrapper<Favorites> favoritesQuery = new LambdaQueryWrapper<>();
            favoritesQuery.eq(Favorites::getUserId, userId)
                    .orderByDesc(Favorites::getCreatedAt);
            List<Favorites> favorites = favoritesService.list(favoritesQuery);

            if (favorites.isEmpty()) {
                return R.success("获取成功", new ArrayList<>());
            }

            // 获取所有收藏的商品ID
            List<Integer> productIds = favorites.stream()
                    .map(Favorites::getProductId)
                    .collect(Collectors.toList());

            // 查询商品信息
            List<Products> products = productsService.listByIds(productIds);

            // 获取农场ID列表
            List<Integer> farmIds = products.stream()
                    .map(Products::getFarmId)
                    .distinct()
                    .collect(Collectors.toList());

            // 获取商品图片
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.in(ProductImages::getProductId, productIds)
                    .eq(ProductImages::getIsPrimary, 1);
            List<ProductImages> allImages = productImagesService.list(imageQuery);

            // 获取农场信息
            Map<Integer, Farms> farmMap = farmsService.listByIds(farmIds)
                    .stream()
                    .collect(Collectors.toMap(Farms::getFarmId, farm -> farm));

            // 按商品ID分组图片
            Map<Integer, String> imageMap = allImages.stream()
                    .collect(Collectors.toMap(
                            ProductImages::getProductId,
                            ProductImages::getImageUrl,
                            (existing, replacement) -> existing
                    ));

            // 构建返回数据
            List<Map<String, Object>> result = new ArrayList<>();
            for (Favorites favorite : favorites) {
                Products product = products.stream()
                        .filter(p -> p.getProductId().equals(favorite.getProductId()))
                        .findFirst()
                        .orElse(null);
                if (product != null) {
                    Farms farm = farmMap.get(product.getFarmId());
                    Map<String, Object> item = new HashMap<>();
                    item.put("productId", product.getProductId());
                    item.put("farmId", product.getFarmId());
                    item.put("productName", product.getProductName());
                    item.put("productImage", imageMap.getOrDefault(product.getProductId(), ""));
                    item.put("farmName", farm != null ? farm.getFarmName() : "未知农场");
                    item.put("price", product.getPrice());
                    item.put("collectTime", favorite.getCreatedAt());
                    item.put("status", product.getStatus());
                    result.add(item);
                }
            }

            log.info("获取收藏列表成功，共 {} 条记录", result.size());
            return R.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取收藏列表失败: {}", e.getMessage(), e);
            return R.error("获取收藏列表失败：" + e.getMessage());
        }
    }
    @GetMapping("/favorites/check/{productId}")
    public R checkIsFavorite(@PathVariable Integer productId, HttpServletRequest request) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        
        log.info("检查收藏状态, userId: {}, productId: {}", userId, productId);
        
        if (userId == null || productId == null) {
            return R.error("参数错误");
        }
        
        try {
            LambdaQueryWrapper<Favorites> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Favorites::getUserId, userId)
                    .eq(Favorites::getProductId, productId);
            
            // 直接返回是否找到记录
            return R.success("获取收藏状态成功", favoritesService.getOne(queryWrapper) != null);
        } catch (Exception e) {
            log.error("检查收藏状态失败", e);
            return R.error("检查收藏状态失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public R getAllProducts() {
        return productsService.getAllProducts();
    }

    /**
     * 获取所有商品列表（管理员用，包含已下架商品）
     * @return 商品列表
     */
    @GetMapping("/admin/list")
    public R getAllProductsForAdmin() {
        log.info("获取所有商品列表（管理员）");
        return productsService.getAllProductsForAdmin();
    }

    @GetMapping("/search")
    public R searchProducts(@RequestParam String keyword) {
        System.out.println("搜索商品, keyword: " + keyword);
        log.info("搜索商品, keyword: {}", keyword);
        return productsService.searchProducts(keyword);
    }

    @GetMapping("/category/{categoryId}")
    public R getProductsByCategory(@PathVariable Integer categoryId) {
        System.out.println("根据分类获取商品, categoryId: " + categoryId);
        log.info("根据分类获取商品, categoryId: {}", categoryId);
        return productsService.getProductsByCategory(categoryId);
    }

    /**
     * 保存商品购买信息到Redis
     * @param productId 商品ID
     * @param quantity 购买数量
     * @param request HttpServletRequest
     * @return R
     */
    @PostMapping("/purchase/prepare")
    public R preparePurchase(
            @RequestParam Integer productId,
            @RequestParam Integer quantity,
            HttpServletRequest request) {
        log.info("准备购买商品, productId: {}, quantity: {}", productId, quantity);
        
        // 获取用户ID
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error("用户未登录");
        }
        
        try {
            // 获取商品详情
            R productDetailResult = productsService.getProductDetail(productId);
            if (!productDetailResult.getSuccess()) {
                return R.error("获取商品信息失败");
            }
            
            Map<String, Object> productDetail = (Map<String, Object>) productDetailResult.getData();
            Products product = (Products) productDetail.get("product");
            Object farmObj = productDetail.get("farm");
            
            if (product == null) {
                return R.error("商品不存在");
            }
            
            // 检查库存
            if (product.getStock() < quantity) {
                return R.error("商品库存不足");
            }
            
            // 创建购买信息DTO
            ProductPurchaseDTO purchaseInfo = new ProductPurchaseDTO();
            purchaseInfo.setProductId(product.getProductId());
            purchaseInfo.setProductName(product.getProductName());
            purchaseInfo.setPrice(BigDecimal.valueOf(product.getPrice()));
            purchaseInfo.setQuantity(quantity);
            purchaseInfo.setTotalAmount(BigDecimal.valueOf(product.getPrice() * quantity));
            purchaseInfo.setUserId(userId);
            
            // 设置农场信息
            if (farmObj != null) {
                if (farmObj instanceof Map) {
                    Map<String, Object> farmMap = (Map<String, Object>) farmObj;
                    purchaseInfo.setFarmId((Integer) farmMap.get("farmId"));
                    purchaseInfo.setFarmName((String) farmMap.get("farmName"));
                } else {
                    // 如果是Farms对象，直接获取属性
                    org.com.pojo.Farms farm = (org.com.pojo.Farms) farmObj;
                    purchaseInfo.setFarmId(farm.getFarmId());
                    purchaseInfo.setFarmName(farm.getFarmName());
                }
            }
            
            // 生成购物车key
            String cartKey = CART_KEY_PREFIX + userId + ":" + productId;
            purchaseInfo.setCartKey(cartKey);
            
            // 保存到Redis，设置5分钟过期
            redisUtil.set(cartKey, purchaseInfo, CART_EXPIRE_TIME);
            
            // 将购物车key添加到用户的购物车key集合中
            String cartSetKey = CART_SET_KEY_PREFIX + userId;
            redisUtil.sSet(cartSetKey, cartKey);
            redisUtil.expire(cartSetKey, CART_EXPIRE_TIME);
            
            return R.success("商品已加入购物车", purchaseInfo);
        } catch (Exception e) {
            log.error("准备购买商品失败", e);
            return R.error("准备购买商品失败：" + e.getMessage());
        }
    }

    /**
     * 获取最新上架的4个商品
     * @return 商品列表
     */
    @GetMapping("/latest")
    public R getLatestProducts() {
        try {
            log.info("获取最新上架商品");
            
            // 查询最新的4个商品
            LambdaQueryWrapper<Products> productsQuery = new LambdaQueryWrapper<>();
            productsQuery.orderByDesc(Products::getCreatedAt)
                    .last("LIMIT 4");
            List<Products> products = productsService.list(productsQuery);
            
            if (products.isEmpty()) {
                return R.success("获取成功", new ArrayList<>());
            }
            
            // 获取农场ID列表
            List<Integer> farmIds = products.stream()
                    .map(Products::getFarmId)
                    .distinct()
                    .collect(Collectors.toList());
                    
            // 获取商品ID列表
            List<Integer> productIds = products.stream()
                    .map(Products::getProductId)
                    .collect(Collectors.toList());

            // 获取商品主图
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.in(ProductImages::getProductId, productIds)
                    .eq(ProductImages::getIsPrimary, 1);
            List<ProductImages> productImages = productImagesService.list(imageQuery);

            // 获取农场信息
            Map<Integer, Farms> farmMap = farmsService.listByIds(farmIds)
                    .stream()
                    .collect(Collectors.toMap(Farms::getFarmId, farm -> farm));

            // 按商品ID分组图片
            Map<Integer, String> imageMap = productImages.stream()
                    .collect(Collectors.toMap(
                            ProductImages::getProductId,
                            ProductImages::getImageUrl,
                            (existing, replacement) -> existing
                    ));

            // 构建返回数据
            List<Map<String, Object>> result = new ArrayList<>();
            for (Products product : products) {
                Map<String, Object> item = new HashMap<>();
                Farms farm = farmMap.get(product.getFarmId());
                
                item.put("productId", product.getProductId());
                item.put("farmId", product.getFarmId());
                item.put("productName", product.getProductName());
                item.put("productDescription", product.getProductDescription());
                item.put("productImage", imageMap.getOrDefault(product.getProductId(), ""));
                item.put("farmName", farm != null ? farm.getFarmName() : "未知农场");
                item.put("price", product.getPrice());
                item.put("createdAt", product.getCreatedAt());
                
                result.add(item);
            }

            log.info("获取最新商品成功，共 {} 条记录", result.size());
            return R.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取最新商品失败: {}", e.getMessage(), e);
            return R.error("获取最新商品失败：" + e.getMessage());
        }
    }
} 